package com.pw.ba.result;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.pw.ba.exception.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.io.Serializable;
import java.util.List;

/**
 * @Auther: zhengzihang
 * @Date: 2018/7/4 15:20
 * @Description: {
 * code: 0,
 * msg: "",
 * count: 1000,
 * data: []
 * }
 * id
 * value
 * label
 * type
 * description
 * sort
 * parentId
 * createBy
 * createDate
 * updateBy
 * updateDate
 * remarks
 * delFlag
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class BaseTableResult<T> implements Serializable {
    public static final int SUCCESS = 0;
    public static final int ERROR = 1;
    @ApiModelProperty(value="状态",name="code",required=true)
    protected Integer code;
    @ApiModelProperty(value="消息",name="msg",required=true)
    protected String msg;
    @ApiModelProperty(value="错误消息",name="erroMsg",required=true)
    protected String erroMsg;
    @ApiModelProperty(value="响应数据",name="data",required=false)
    protected T data;

    public BaseTableResult() {
    }

    public BaseTableResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public BaseTableResult(Integer code, String msg, String erroMsg, T data) {
        this.code = code;
        this.msg = msg;
        this.erroMsg = erroMsg;
        this.data = data;
    }

    /**
     * valid框架校验参数
     *
     * @param result
     */
    public static void checkParams(BindingResult result) {
        if (result.hasErrors()) {
            List<FieldError> errorList = result.getFieldErrors();
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError error : errorList) {
                System.out.println(error.getField() + "*" + error.getDefaultMessage());
                if (StringUtils.isNotBlank(error.getDefaultMessage())) {
                    stringBuilder.append(error.getDefaultMessage() + ",");
                } else {
                    stringBuilder.append(error.getField() + "不能为空,");
                }
            }
            throw new ServiceException(stringBuilder.substring(0, stringBuilder.length() - 1));
        }
    }

    public boolean OK() {
        return this.code == SUCCESS;
    }

    public boolean ERROR() {
        return this.code == ERROR;
    }
}
